<template>
  <div class="sn">
    <sninfo-details :online="is_online" :studentStatus="studentStatus" :snData="sn" v-if="detailsShow" @sninfoClose="sninfoClose"></sninfo-details>

    <div v-else>
      <div class="header_search " v-if="searchShow">
        <el-form size="mini">
          <div class="flex flex-wrap">
            <el-form-item label="SN码" class="searchI" label-width="120px">
              <el-input size="mini" v-model="listQuery.value" placeholder="请输入SN码"></el-input>
            </el-form-item>
            <el-form-item label="归属" class="searchI" label-width="120px">
              <el-select v-model="listQuery.username" placeholder="请选择归属" size="mini" style="width:163px" filterable @change="infoChange">
                <el-option v-for="(item,index) in snParams" :key="index" :label="`${item.username} - ${item.title}
              ${item.a_username != null ? '('+ item.a_username + '-' + item.a_title +')' : ''}`" :value="item.username"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="批次" class="searchI" label-width="120px">
              <el-select v-model="listQuery.batch" placeholder="请选择批次" size="mini" style="width:163px">
                <el-option v-for="(item,index1) in batchArray" :key="index1" :label="item.batch" :value="item.batch"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="学号" class="searchI" label-width="120px">
              <el-input size="mini" v-model="listQuery.sno" placeholder="请输入学号"></el-input>
            </el-form-item>
            <el-form-item label="姓名" class="searchI" label-width="120px">
              <el-input size="mini" v-model="listQuery.s_realname" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="系统固件版本号" class="searchI" label-width="120px">
              <el-input size="mini" v-model="listQuery.devices_version" placeholder="请输入系统固件版本号"></el-input>
            </el-form-item>
            <el-form-item label="设备信息版本号" class="searchI" label-width="120px">
              <el-input size="mini" v-model="listQuery.appstore_version" placeholder="请输入设备信息版本号"></el-input>
            </el-form-item>
            <el-form-item label="教管壹版本号" class="searchI" label-width="120px">
              <el-input size="mini" v-model="listQuery.store_version" placeholder="请输入教管壹版本号"></el-input>
            </el-form-item>
            <el-form-item label="屏幕状态" class="searchI" label-width="120px">
              <el-select v-model="listQuery.is_screen_lock" placeholder="请选择屏幕状态" size="mini" style="width:163px">
                <el-option label="锁屏" value="1"></el-option>
                <el-option label="使用中" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="在线状态" class="searchI" label-width="120px">
              <el-select v-model="listQuery.is_online" placeholder="请选择在线状态" style="width:163px">
                <el-option label="在线" value="1"></el-option>
                <el-option label="离线" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="激活条件" class="searchI" label-width="120px">
              <el-select v-model="listQuery.is_activate" placeholder="请选择激活状态" style="width:163px">
                <el-option label="激活" value="1"></el-option>
                <el-option label="未激活" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="searchI" label-width="120px">
              <div class="flex felx_align">
                <el-button size="mini" type="primary" @click="getquerySn()">提交</el-button>
                <el-button size="mini" @click="restParams">重置</el-button>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <!-- 头部 -->
      <div class="table_header flex flex_bet flex-wrap">
        <div class="table_button flex felx_align flex-wrap">
          <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
          <el-button v-permission="['超级管理员','管理员']" type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
          <el-button v-permission="['超级管理员','管理员']" type="primary" icon="el-icon-download" size="mini" @click="getimportSn">导入</el-button>
          <el-button type="primary" icon="el-icon-upload2" size="mini" @click="exporFormVisible = true">导出</el-button>
          <el-button v-permission="['超级管理员']" type="primary" icon="el-icon-document-copy" size="mini" @click="batchEditVisible = true">修改设备类型与套餐</el-button>
          <el-button type="primary" icon="el-icon-document-copy" size="mini" @click="bathFormVisible = true">批次管理</el-button>
          <el-button type="primary" v-permission="['超级管理员','管理员']" icon="el-icon-delete" size="mini" @click="deleteFormVisible = true">批量删除</el-button>
          <el-button type="primary" size="mini" @click="handleDownload">批次创立更新导入模板<i class="el-icon-paperclip el-icon--right"></i></el-button>
          <el-button v-permission="['超级管理员']" type="primary" size="mini" @click="downloadSnPlatter">更新模板<i class="el-icon-paperclip el-icon--right"></i></el-button>
          <div class="guidetext" @click="imgShow = true"><i class="iconfont iconiconfontwenhao1 guide"></i>操作指引</div>
        </div>
        <div class="table_searchs flex felx_align">
          <div class="table_search flex">
            <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small" maxlength="30">
              <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:140px">
                <el-option label="sn码" value="value"></el-option>
                <el-option label="归属" value="username"></el-option>
                <el-option label="批次" value="batch"></el-option>
                <el-option label="学号" value="sno"></el-option>
                <el-option label="姓名" value="s_realname"></el-option>
                <el-option label="班级" value="classlevel"></el-option>
                <el-option label="系统固件版本号" value="devices_version"></el-option>
                <el-option label="设备信息版本号" value="appstore_version"></el-option>
                <el-option label="教管壹版本号" value="store_version"></el-option>
                <!-- <el-option label="在线状态" value="is_online"></el-option> -->
              </el-select>
              <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
            </el-input>
          </div>
          <el-button size="mini" type="primary" style="margin:0 8px" icon="iconfont iconshaixuan2" @click="searchShows"></el-button>
          <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
        </div>
      </div>
      <!-- SN的table内容 -->
      <el-table :data="tableData" stripe style="width: 100%" :key="key" border fit highlight-current-row ref="tableDataRef" @sort-change="tableSortCge" max-height="592">
        <el-table-column v-if="colData[0].istrue" min-width="130" align="center" prop="username" label="归属" fixed></el-table-column>
        <el-table-column v-if="colData[1].istrue" min-width="100" align="center" prop="batch" label="批次" fixed></el-table-column>
        <el-table-column v-if="colData[2].istrue" min-width="160" align="center" prop="value" label="SN码" fixed>
          <template slot-scope="scope">
            <div class="flex flex_spa">
              <el-link :type="scope.row.is_lock ? 'primary' : 'danger'" @click="snInfoShow(scope.row.value,scope.row)">
                {{scope.row.value}}<i class="iconfont iconjiesuo1" style="margin-left:5px" v-if="!scope.row.is_lock"></i>
              </el-link>
              <i class="cobyOrderSn iconfont iconother_fuzhi" :data-clipboard-text="scope.row.value" @click="copy"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column  min-width="100" align="center" prop="sn_type" label="设备类型" fixed></el-table-column>
        <el-table-column min-width="100" align="center" prop="platter" label="学习套餐" fixed></el-table-column>
        <el-table-column v-if="colData[3].istrue" min-width="140" align="center" prop="mac" label="设备MAC地址">
          <template slot-scope="scope">
            <div @click="getqueryIdSn(scope.row.id)">{{scope.row.mac}}</div>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[4].istrue" min-width="100" align="center" prop="classlevel" label="班级"></el-table-column>
        <el-table-column v-if="colData[5].istrue" min-width="80" align="center" prop="sno" label="学号"></el-table-column>
        <el-table-column v-if="colData[6].istrue" min-width="80" align="center" prop="realname" label="姓名"></el-table-column>
        <el-table-column v-if="colData[7].istrue" min-width="110" align="center" prop="phone" label="监护人1 (号码)"></el-table-column>
        <el-table-column v-if="colData[8].istrue" min-width="110" align="center" prop="phone_two" label="监护人2 (号码)"></el-table-column>
        <el-table-column v-if="colData[9].istrue" min-width="280" align="center" prop="devices_version" label="ROM版本号"></el-table-column>
        <el-table-column v-if="colData[10].istrue" min-width="180" align="center" prop="appstore_version" label="设备信息版本号" sortable="custom"></el-table-column>
        <el-table-column v-if="colData[11].istrue" min-width="160" align="center" prop="store_version" label="教管壹版本号" sortable="custom"></el-table-column>
        <el-table-column v-if="colData[12].istrue" min-width="80" align="center" prop="is_screen_lock  " label="屏幕状态">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="light" :content="scope.row.is_screen_lock ? '设备处于锁屏状态中' : '设备正常使用中'" placement="top-start">
              <span class="iconfont iconweibiaoti559" :class="scope.row.is_screen_lock ? 'lock' : ''" style="font-size:20px"></span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[13].istrue" min-width="110" align="center" label="在线状态" width="100">
          <template slot-scope="scope">
            <div class="flex flex_cen felx_align">
              <div class="state flex flex_cen" :class="scope.row.is_online == 1 ? 'on_line' : 'off_line'">
                <span>{{scope.row.is_online == 1 ? '在线' : '离线'}}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column  min-width="140" align="center" prop="offlinetime" label="离线时间" sortable="custom">
          <template slot-scope="scope">{{scope.row.offlinetime | newDate }}</template>
        </el-table-column>
        <el-table-column v-if="colData[15].istrue" min-width="130" align="center" prop="e_create_time" label="首次激活时间" sortable="custom">
          <template slot-scope="scope">{{scope.row.e_create_time| activationTime}}</template>
        </el-table-column>
        <el-table-column v-if="colData.length > 16 ? colData[16].istrue : false" min-width="110" align="center" prop="createtime" label="上传时间" sortable="custom">
          <template slot-scope="scope">{{scope.row.createtime| numberDays}}</template>
        </el-table-column>
        <el-table-column min-width="110" align="center" prop="warranty" label="保修期"></el-table-column>
        <el-table-column min-width="110" align="center" prop="control_time" label="管控期"></el-table-column>
        <el-table-column min-width="110" align="center" prop="is_qid" label="可换qid"> </el-table-column>
        <el-table-column min-width="110" align="center" prop="remark"  label="其他备注"></el-table-column>

        <!-- table按钮编辑和删除 -->
        <el-table-column label="操作" width="210" align="center">
          <template slot-scope="scope">
            <el-row>
              <el-button type="primary" @click="getqueryIdSn(scope.row.id)" size="mini">操作</el-button>
              <el-button v-permission="['超级管理员','管理员']" size="mini" @click="getdeleteSn(scope.row)">删除</el-button>
              <el-button size="mini" @click="getsingleSnScreen(scope.row)">控制</el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="paging">
        <el-pagination :current-page.sync="listQuery.startSize" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]" :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total" background></el-pagination>
      </div>
    </div>
    <!-- 弹窗 -->
    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
    <!-- 添加弹窗 -->
    <el-dialog title="添加" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="30%">
      <el-form :model="addForm" :rules="rules" ref="ruleForm">
        <el-form-item label="SN码" label-width="100px" prop="value">
          <el-input v-model="addForm.value" autocomplete="off" placeholder="请输入SN码"  maxlength="30" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="设备类型" label-width="100px" prop="sn_type">
          <el-select v-model="addForm.sn_type" placeholder="请选择" style="width: 200px">
            <el-option
              v-for="item in snTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可生成qid" label-width="100px" prop="is_qid">
          <el-radio-group v-model="addForm.is_qid">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="-1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="保修期" label-width="100px" prop="warranty" >
          <el-input v-model="addForm.warranty" placeholder="请输入保修期" type="number" style="width: 200px"></el-input>个月
        </el-form-item>
        <el-form-item label="管控期" label-width="100px" prop="control_time">
          <el-input v-model="addForm.control_time" placeholder="请输入管控期期" type="number" style="width: 200px"></el-input>个月
        </el-form-item>
        <el-form-item label="归属" label-width="100px" prop="username">
          <el-select v-model="addForm.username" placeholder="请选择归属" filterable style="width: 200px">
            <el-option v-for="(item,index) in agentsAdmin" :key="index" :label="`${item.username}-${item.realname ? item.realname : ''} (${item.title})`" :value="item.username"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学习套餐" label-width="100px" prop="platter_id">
          <el-select v-model="addForm.platter_id" placeholder="请选择" style="width: 200px">
            <el-option
              v-for="item in platterOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-permission="['超级管理员']" label="其他备注" label-width="100px" prop="remark">
          <el-input v-model="addForm.remark" autocomplete="off" placeholder="请输入备注"  class="add_select"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" @click="postAscription('ruleForm')" size="mini" round>确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑弹窗 -->
    <el-dialog title="编辑" :visible.sync="redactFormVisible" @close="redactFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="30%">
      <el-form :model="redactForm" ref="redactForm" size="mini" :rules="redactRules">
        <el-form-item label="SN码" label-width="130px" prop="value">
          <el-input v-model="redactForm.value" autocomplete="off" placeholder="请输入12位的SN码" class="add_select" disabled></el-input>
        </el-form-item>
        <el-form-item  label="设备类型" label-width="130px" prop="sn_type">
          <el-select v-model="redactForm.sn_type" placeholder="请选择" class="add_select" :disabled="forbid">
            <el-option
              v-for="item in snTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可生成qid" label-width="130px" prop="is_qid" v-if="isAdmin">
          <el-radio-group v-model="redactForm.is_qid" :disabled="setQid">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="-1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item  label="保修期" label-width="130px" prop="warranty" >
          <el-input v-model="redactForm.warranty" placeholder="请输入保修期" type="number" style="width: 200px" :disabled="forbid"></el-input>个月
        </el-form-item>
        <el-form-item  label="管控期" label-width="130px" prop="control_time">
          <el-input v-model="redactForm.control_time" placeholder="请输入管控期期" type="number" style="width: 200px" :disabled="forbid"></el-input>个月
        </el-form-item>
        <el-form-item label="归属" label-width="130px" prop="username">
          <el-select v-model="redactForm.username" placeholder="请选择归属" class="add_select" @change="changeParams" :disabled="this.forbid" filterable>
            <el-option v-for="(item,index) in snParams" :key="index" :label="`${item.username}  (${item.title})`" :value="item.username"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item  label="学习套餐" label-width="130px" prop="platter_id" v-show="redactForm.is_qid==1">
          <el-select v-model="redactForm.platter_id" placeholder="请选择" class="add_select" :disabled="forbid">
            <el-option
              v-for="item in platterOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="批次" label-width="130px">
          <el-select v-model="redactForm.batch" placeholder="请选择批次" class="add_select" filterable>
            <el-option v-for="item in redactParams" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" label-width="130px" prop="value">
          <el-input v-model="redactForm.classlevel" autocomplete="off" placeholder="请输入班级(不能超过12位)" maxlength="12" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="学号" label-width="130px" prop="value">
          <el-input v-model="redactForm.sno" autocomplete="off" placeholder="请输入学号不能超过12位)" maxlength="12" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="姓名" label-width="130px" prop="value">
          <el-input v-model="redactForm.realname" autocomplete="off" placeholder="请输入姓名不能超过12位)" maxlength="12" class="add_select"></el-input>
        </el-form-item>
        <el-form-item v-permission="['超级管理员']" label="其他备注" label-width="130px" prop="remark">
          <el-input v-model="redactForm.remark" autocomplete="off" placeholder="请输入备注"  class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="监护人1（号码）" label-width="130px">
          <el-input v-model="redactForm.phone" autocomplete="off" placeholder="请输入监护人1（号码）" maxlength="11" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="监护人2（号码）" label-width="130px" prop="phone_two">
          <el-input v-model="redactForm.phone_two" autocomplete="off" placeholder="请输入监护人2（号码）" maxlength="11" class="add_select"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="redactFormVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" @click="geteditSn('redactForm')" size="mini" round>确 定</el-button>
      </div>
    </el-dialog>
    <!-- SN码导入 -->
    <el-dialog title="SN码导入" :visible.sync="loadFormVisible" @close="snFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
      <el-form :model="SnForm" :rules="rules" ref="snFormclose">
        <el-form-item label="归属用户" label-width="130px" prop="batch">
          <el-select v-model="SnForm.batch" placeholder="请选择归属" @change="snSelectChange" filterable>
            <el-option v-for="(item,index) in agentsAdmin" :key="index" :label="`${item.username}-${item.realname ? item.realname : ''} (${item.title})`" :value="item.username"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导入文件" label-width="130px" class="snElsx" prop="file">
          <div>
            <el-input autocomplete="off" placeholder="请点击上传，上传xls或xlsx文件" v-model="SnForm.file.name"></el-input>
            <upload-excel-component style=" flex:1" class="flex mrg-top" :on-success="handleSuccess" :before-upload="beforeUpload" :loading="!videoFlag" :disabled="snDisabled" @submitXlsx="submitXlsxSn">
              <span>{{videoFlag ? '' : goodsData + '%'}}</span>
            </upload-excel-component>
          </div>
        </el-form-item>
        <div v-if="snShow">
          <el-form-item label="成功导入:" label-width="130px" style="margin-bottom:0">共{{ this.snData.succeed}}条</el-form-item>
          <el-form-item label="导入失败:" label-width="130px" style="margin-bottom:0"> 共{{ this.snData.fail.length}}条</el-form-item>
          <el-form-item label="相同的SN:" label-width="130px" style="margin-bottom:0"> 共{{ this.snData.sameData}}条
            {{ this.snData.same.length >= 1 ? `( 位于:第${this.snData.same.toString()}行 ), 只展示前10行` : ''}}
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="loadFormVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" @click="uploadButton" size="mini" round>确 定</el-button>
      </div>
    </el-dialog>
    <!-- SN码导出 -->
    <el-dialog title="SN码导出" :visible.sync="exporFormVisible" :close-on-click-modal="false" @close="exporFormclose" :close-on-press-escape="false" width="35%">
      <el-form :model="exporForm">
        <el-form-item label="导出类型:" label-width="130px">
          <el-radio-group v-model="exporForm.type" @change="brandclassifySelect">
            <el-radio label="1">导出全部</el-radio>
            <el-radio label="2">导出无批次</el-radio>
            <el-radio label="3">按归属导出</el-radio>
            <el-radio label="4">按批次导出</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择归属:" label-width="130px">
          <el-select v-model="exporForm.username" placeholder="请选择归属" class="add_select" :disabled="exporDisabled" filterable>
            <el-option v-for="(item,index) in snParams" :key="index" :label="`${item.username}-${item.realname ? item.realname : ''} (${item.title})`" :value="item.username"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择批次:" label-width="130px">
          <el-select v-model="exporForm.batch" placeholder="请选择批次" class="add_select" :disabled="batchDisabled">
            <el-option v-for="(item,index) in redactParams" :key="index" :label="item.batch" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exporFormVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" @click="getdownloadSn" size="mini" round>确 定</el-button>
      </div>
    </el-dialog>
    <!-- SN批次管理 -->
    <el-dialog title="批次管理" :visible.sync="bathFormVisible" @close="bathFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
      <el-form :model="bathForm">
        <el-form-item label="选择批次:" label-width="130px">
          <el-select v-model="bathForm.batch" placeholder="请选择批次" @change="batchSelectChange" no-data-text="无数据：请在 '管控批次管理' 创立管控的批次" filterable>
            <el-option v-for="item in tathArray" :key="item.id" :label="item.batch" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备管理:" label-width="130px">
          <el-radio-group v-model="bathForm.type">
            <el-radio :label="1">恢复出厂</el-radio>
            <el-radio :label="0">不恢复出厂</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="导入文件" label-width="130px" class="snElsx">
          <div>
            <el-input autocomplete="off" placeholder="请点击上传，上传xls或xlsx文件" v-model="bathForm.pathname"></el-input>
            <el-tooltip :disabled="!gerentDisabled" class="item mrg-top" effect="dark" content="请先选择批次方可上传" placement="top-start">
              <upload-excel-component class="flex" :disabled="gerentDisabled" :before-upload="batchUpload" :loading="!videoFlag" @submitXlsx="submitXlsx">
                <span>{{videoFlag ? '' : goodsData + '%'}}</span>
              </upload-excel-component>
            </el-tooltip>
          </div>
        </el-form-item>
        <div v-if="batchShow">
          <el-form-item label="成功导入:" label-width="130px" style="margin-bottom:0">共{{ snData.succeed}}条</el-form-item>
          <el-form-item label="导入失败:" label-width="130px" style="margin-bottom:0"> 共{{ snData.sameData}}条
            {{ this.snData.same.length >= 1 ? `( 位于:第${this.snData.same.toString()}行 ), 只展示前10行` : ''}}
          </el-form-item>
          <el-form-item label="总条数:" label-width="130px" style="margin-bottom:0">共{{snData.all}}条</el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bathFormVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" @click="bathFormVisible = false" size="mini" round>确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog  title="修改设备类型与套餐" :visible.sync="batchEditVisible" @close="batchEditClose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
      <el-form :model="batchEditForm">
        <el-form-item label="设备管理:" label-width="130px">
          <el-radio-group v-model="batchEditForm.type">
            <el-radio :label="1">恢复出厂</el-radio>
            <el-radio :label="0">不恢复出厂</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="导入文件" label-width="130px" class="snElsx">
          <div>
            <el-input autocomplete="off" placeholder="请点击上传，上传xls或xlsx文件" v-model="batchEditForm.pathname"></el-input>
              <upload-excel-component class="flex"  :before-upload="batchEditUpload" :loading="!videoFlag" @submitXlsx="submitBatchEditXlsx">
                <span>{{videoFlag ? '' : goodsData + '%'}}</span>
              </upload-excel-component>
          </div>
        </el-form-item>
        <div v-if="batchShow">
          <el-form-item label="成功:" label-width="130px" style="margin-bottom:0">共{{ snData.succeed}}条</el-form-item>
          <el-form-item label="失败:" label-width="130px" style="margin-bottom:0"> 共{{ snData.sameData}}条
            {{ this.snData.same.length >= 1 ? `( 位于:第${this.snData.same.toString()}行 ), 只展示前10行` : ''}}
          </el-form-item>
          <el-form-item label="总条数:" label-width="130px" style="margin-bottom:0">共{{snData.all}}条</el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchEditVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" @click="batchEditVisible = false" size="mini" round>确 定</el-button>
      </div>
    </el-dialog>

    <!-- 模板操作图片弹窗 -->
    <div class="component" v-if="imgShow">
      <div class="mbImg"><img src="@/assets/images/snTemplate.png" alt=""></div>
      <div class="masking" @click="imgShow = false"></div>
    </div>

    <!-- 批量删除弹窗 -->
    <el-dialog title="批量删除" class="aabb" :visible.sync="deleteFormVisible" @close="deleteFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
      <el-form :model="deleteForm">
        <el-form-item label="导入文件" label-width="80px" class="snElsx">
          <div>
            <el-input autocomplete="off" placeholder="请点击上传，上传xls或xlsx文件" v-model="deleteForm.file.name"></el-input>
            <upload-excel-component class="flex mrg-top" :before-upload="deleteUpload" :loading="!videoFlag" @submitXlsx="submitXlsxDelete">
              <span>{{videoFlag ? '' : goodsData + '%'}}</span>
            </upload-excel-component>
          </div>
        </el-form-item>
        <div v-if="deleteShow">
          <el-form-item label="成功导入:" label-width="130px" style="margin-bottom:0">共{{ deleteData.succeed}}条</el-form-item>
          <el-form-item label="导入失败:" label-width="130px" style="margin-bottom:0">共{{ deleteData.error}}条</el-form-item>
          <el-form-item label="相同的SN码:" label-width="130px" style="margin-bottom:0"> 共{{ deleteData.sameData}}条
            {{ this.deleteData.same.length >= 1 ? `( 位于:第${this.deleteData.same.toString()}行 ), 只展示前10行` : ''}}
          </el-form-item>
          <el-form-item label="总条数:" label-width="130px" style="margin-bottom:0">共{{deleteData.all}}条</el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteFormVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" @click="deleteFormVisible = false" size="mini" round>确 定</el-button>
      </div>
    </el-dialog>

    <!-- 锁屏与解锁弹窗start -->
    <el-dialog title="远程锁屏" :visible.sync="screenShow" :close-on-click-modal="false" :close-on-press-escape="false" width="25%" @close="screenFormclose">
      <el-form :model="screenDate">
        <div style="line-height: 24px;font-size: 14px;margin-bottom: 10px;">{{screenDate.text ? '取消锁屏状态，用户将可以正常使用' : '发送锁屏指令，用户无法正常使用。'}}</div>
        <el-form-item class="snElsx">
          <div class="addPut">
            <el-input type="textarea" placeholder="因管控需要，该设备锁定中，请联系老师或管理员" :maxlength="60" :rows="4" v-model="screenDate.value" show-word-limit />
            <div class="screen">(限定输入60个字符)</div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="screenShow = false" size="mini" round>取 消</el-button>
        <el-button type="primary" size="mini" round @click="screenPrimary">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 锁屏与解锁弹窗end -->
  </div>
</template>

<script>
import UploadExcelComponent from "@/components/UploadExcelSn/index.vue";
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import snDialog from "@/components/snDialog"
import deleteDialog from "@/components/deleteDialog";
import battery from "@/components/electric"
import permission from '@/directive/permission/index.js' // 权限判断指令
import forbid from '@/directive/permission/forbid.js'
import Clipboard from 'clipboard'; //复制功能
import { Loading } from 'element-ui';
import {
  querySn, deleteSn, getAscription, postAscription, queryIdSn, editSn, getBatch, downloadSn, importSn, getBatchTwo, batchManager, launchScreenshot, querySnScreens, deleteAll, getEquip,
  refreshEquipParam, getAppBySn, singleSnReset, singleSnRestart, forceStopApp, singleSnScreen, importDeleteSn, getAgentUser
} from "@/api/equipment.js";
import { queryUsernameBatch } from "@/api/appUpdate.js";
import { mapState } from 'vuex'
import WebsocketSn from './components/websocketSn'
import sninfoDetails from './components/sninfoDetails'
import {batchEditSNInfo} from "@/api/equipment";
import mqttHandle from "@/utils/mqttHandler";
var client = null;  //mqtt的实力
export default {
  directives: { permission },
  components: { UploadExcelComponent, dynamicTable, snDialog, battery, deleteDialog, WebsocketSn, sninfoDetails },
  data() {
    var phoneReg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('号码不能为空!'))
      }
      if (!phoneReg.test(value)) {
        callback(new Error('手机号码有误'))
      } else {
        callback()
      }
    };
    return {
      checkboxVal: ['归属', '批次', 'SN码', '设备MAC地址', '班级', '学号', '姓名', '监护人1', '监护人2', '系统固件版本号', '设备信息版本号', '教管壹版本号', "屏幕状态", "在线状态", '离线时间', '首次激活时间', '上传时间'],
      key: 1,
      colData: [], //动态控制table
      select: "value", //搜索条件
      searchTable: "",
      total: 0, //总数量
      tableData: [],
      //添加弹窗控制
      dialogFormVisible: false,
      //添加表单
      addForm: { value: "", username: "", sn_type:"", warranty:"", control_time:"", platter_id:"", is_qid:-1, remark: ''},
      rules: {
        value: [{ required: true, message: "请输入SN码", trigger: "blur" }],
        batch: [{ required: true, message: "请选择归属", trigger: "blur" }],
        sn_type: [{ required: true, message: "请选择设备类别", trigger: "blur" }]
      },
      //归属列表
      snParams: [],
      //设备维护获取批次信息
      redactParams: [],
      redactFormVisible: false,
      redactForm: { value: '', username: '', batch: '', classlevel: '', sno: '', realname: '', phone: '', phone_two: '',sn_type:"", warranty:"", control_time:"", platter_id:"", is_qid:-1, remark: ''},
      redactRules: { phone: [{ required: true, validator: validatePhone, trigger: 'blur' }], },
      subjectId: 0,
      //sn导入弹窗
      loadFormVisible: false,
      //导入表单
      SnForm: { batch: "", name: '', file: {} },
      //控制上传按钮
      snDisabled: true,
      //导入显示
      snShow: false,
      //上传后显示的数据
      snData: { same: [], sameData: 0, fail: [], succeed: '', all: '' },
      exporFormVisible: false,
      //导出表单批次控制
      batchDisabled: true,
      //导出表单选择器控制
      exporDisabled: true,
      //导出表单
      exporForm: { type: '1', username: '', batch: '' },
      //批次管理
      bathFormVisible: false,
      batchEditVisible: false,
      bathForm: { batch: '', pathname: '', file: {}, type: 0 },
      batchEditForm: {pathname: '', file: {}, type: 0},
      tathArray: [],
      gerentDisabled: true,
      batchShow: false,
      //sn设备信息控制
      snInfo: false,
      infoSn: '',
      listQuery: {
        startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), value: undefined, username: undefined, batch: undefined,
        devices_version: undefined, appstore_version: undefined, store_version: undefined, is_online: undefined, sort: '', sno: undefined, s_realname: undefined, is_screen_lock: undefined, is_activate: undefined
      },
      affiliation: { username: '', batch: '' },//归属逻辑
      //批次模板控制
      imgShow: false,
      videoFlag: true,
      //删除弹窗
      deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
      //批次删除弹窗
      deleteFormVisible: false,
      deleteForm: { file: {} },
      deleteData: {},
      deleteShow: false,
      snHover: 0,
      //锁屏控制
      screenShow: false,
      screenDate: { text: 1, value: '', id: 0 },
      forbid: Boolean,
      searchShow: false,
      userName: '',
      AgentUser: [],
      batchArray: [],
      is_online: 2,
      agentsAdmin: [],
      uploadLink: process.env.VUE_APP_BASE_API,
      sn: undefined,
      detailsShow: false,
      studentStatus: {},
      snTypeOptions: [{label:'教管壹B端', value:1},{label: '教管壹C端', value: 2},{label: '学习机', value: 3},{label: '工业平板', value: 4}],
      platterOptions: [{id:1,name:'A'}],
      isAdmin: false,
      setQid: false,
      topicSends: [], //订阅的topic 例如：["Time1", "EngineMain1", "Console1", "Location1"]
    }
  },
  computed: {
    ...mapState({//获取上传滚动条
      goodsData: state => state.user.progress
    })
  },
  created() {
    //代理商和学习不要显示上传时间
    if (localStorage.getItem("roleName") == '代理商' || localStorage.getItem("roleName") == '学校') {
      this.checkboxVal.pop()
    }
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.getquerySn()
    this.getAscriptions()
    this.getBatch()
    this.getBatchTwo()
    this.forbid = forbid(['超级管理员', '管理员'])
    this.getAgentUsers()//获取代理商
    if(localStorage.getItem("roleName") == '超级管理员') {
      this.isAdmin = true
    }
  },
  methods: {
    sninfoClose() {
      this.detailsShow = false
    },
    //点击sn查询设备信息
    snInfoShow(sn, item) {
      //解锁状态下，无法弹出设备信息窗口
      this.infoSn = sn
      //if (type == 0) return this.$message.error('该设备已解锁')
      this.sn = sn
      //this.snInfo = true
      this.studentStatus = item
      this.is_online = item.is_online
      this.detailsShow = true
    },
    batchEditClose() {
      this.$nextTick(() => {
        this.batchShow = false
        this.batchEditForm = {pathname: '', file: {}, type: 0 }
        this.videoFlag = true
      })
    },
    infoChange(val) {
      this.listQuery.batch = undefined
      this.getqueryUsernameBatch(val)
    },
    //根据用户获取批次
    getqueryUsernameBatch(name) {
      queryUsernameBatch({ username: name }).then(res => {
        this.batchArray = res.data
      }).catch(err => {
        this.batchArray = []
      })
    },
    searchShows() {
      this.searchShow = !this.searchShow
    },
    //复杂查询
    restParams() {
      this.listQuery = {
        startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), type: 1, value: undefined, username: undefined, batch: undefined,
        devices_version: undefined, appstore_version: undefined, store_version: undefined, is_online: undefined, sort: '', sno: undefined, s_realname: undefined
      }
    },
    //表格排序事件
    tableSortCge(column) {
      let order = ''
      column.order == "descending" ? order = 'desc' : order = 'asc'
      let sort = [{ field: column.prop, sort: order }]
      this.listQuery.sort = JSON.stringify(sort)
      this.getquerySn()
    },
    //复制事件
    copy() {
      var clipboard = new Clipboard('.cobyOrderSn')
      clipboard.on('success', e => {
        clipboard.destroy()// 释放内存
      })
      clipboard.on('error', e => {
        this.$message.error('该浏览器不支持请手动复制')
        clipboard.destroy()
      })
    },
    //批次删除事件
    submitXlsxDelete() {
      var fd = new FormData()
      fd.append('file', this.deleteForm.file)
      fd.append('userId', localStorage.getItem("ID"))
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      this.videoFlag = false
      importDeleteSn(fd).then(res => {
        this.deleteShow = true
        this.deleteData.error = res.data.error.length
        this.deleteData.sameData = res.data.noSn.length
        this.deleteData.same = JSON.parse(JSON.stringify(res.data.noSn.splice(0, 10)))
        this.deleteData.succeed = res.data.excelSuccess
        this.deleteData.all = res.data.total
        this.$message.success(res.msg)
        this.videoFlag = true
        this.getquerySn()
      }).catch(err => {
        this.videoFlag = true
      })
    },
    deleteUpload(file) {
      this.deleteForm.file = file
    },
    //删除sn
    getdeleteSn(item) {
      this.deleteDialogs.deleteText = item.value
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = item.id
    },
    //删除SN按钮事件
    deleteEvents() {
      let params = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), id: this.deleteDialogs.deleteId }
      deleteSn(params).then(res => {
        this.$message.success(res.msg)
        this.getquerySn()
      })
    },
    //监听归属下拉
    changeParams(val) {
      //当选中的不是自己的归属，需把批次给清空
      if (val != this.affiliation.username) {
        this.redactParams = []
        this.redactForm.batch = ''
      } else {
        this.redactForm.batch = this.affiliation.batch
        this.getBatch()
      }
    },
    //锁屏与开屏
    getsingleSnScreen(row) {
      //let status = row.is_screen_lock == 1 ? '取消锁屏状态，用户将可以正常使用' : '发送锁屏指令，用户无法正常使用。'
      this.screenDate.text = row.is_screen_lock
      this.screenDate.id = row.id
      this.screenShow = true
      // if (row.batch) {
      //   this.screenShow = true
      // } else {
      //   this.$message('该设备暂未分配批次, 请分配批次后再进行冻屏操作！')
      // }
    },
    screenPrimary() {
      let data = {
        userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), id: this.screenDate.id, type: this.screenDate.text == 1 ? 2 : 1,
        lock_content: this.screenDate.value ? this.screenDate.value : '因管控需要，该设备锁定中，请联系老师或管理员'
      }
      singleSnScreen(data).then(res => {
        this.$message({ type: 'success', message: res.msg });
        this.getquerySn()
        this.screenShow = false
      }).catch(err => {
        this.screenShow = false
      })
    },
    getBatchTwo() {
      getBatchTwo({ userId: localStorage.getItem("ID") }).then(res => {
        this.tathArray = res.data
      }).catch(err => {
        this.tathArray = []
      })
    },
    batchSelectChange(val) {
      this.gerentDisabled = !val
    },
    //批次管理
    submitXlsx() {
      var fd = new FormData()
      fd.append('file', this.bathForm.file)
      fd.append('userId', localStorage.getItem("ID"))
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      fd.append('batch', this.bathForm.batch)
      fd.append('type', this.bathForm.type)
      this.videoFlag = false;
      batchManager(fd).then(res => {
        this.batchShow = true
        this.snData.sameData = res.data[1].length
        this.snData.same = JSON.parse(JSON.stringify(res.data[1]))
        this.snData.succeed = res.data.excelSuccess
        this.snData.all = res.data.total
        this.$message.success(res.msg)
        this.videoFlag = true
        this.getquerySn()
      }).catch(err => {
        this.videoFlag = true;
      })
    },
    submitBatchEditXlsx() {
      var fd = new FormData()
      fd.append('file', this.batchEditForm.file)
      fd.append('userId', localStorage.getItem("ID"))
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      fd.append('type', this.batchEditForm.type)
      this.videoFlag = false;
      batchEditSNInfo(fd).then(res => {
        this.batchShow = true
        this.snData.sameData = res.data[1].length
        this.snData.same = JSON.parse(JSON.stringify(res.data[1]))
        this.snData.succeed = res.data.excelSuccess
        this.snData.all = res.data.total
        this.$message.success(res.msg)
        this.videoFlag = true
        this.getquerySn()
      }).catch(err => {
        this.videoFlag = true;
      })
    },
    batchUpload(file) {
      this.bathForm.file = file
      this.bathForm.pathname = file.name
    },
    batchEditUpload(file) {
      this.batchEditForm.file = file
      this.batchEditForm.pathname = file.name
    },
    //execl导入SN
    getimportSn() {
      this.loadFormVisible = true
    },
    snSelectChange(val) {
      this.snDisabled = !val
    },
    //SN码导入上传
    submitXlsxSn() {
      var fd = new FormData()
      fd.append('file', this.SnForm.file)
      fd.append('userId', localStorage.getItem("ID"))
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      fd.append('username', this.SnForm.batch)
      this.videoFlag = false;
      console.log(this.SnForm);
      importSn(fd).then(res => {
        this.snShow = true
        this.snData.sameData = res.data[0].length
        this.snData.same = JSON.parse(JSON.stringify(res.data[0]))
        this.snData.fail = res.data[2]
        this.snData.succeed = res.data.excelSuccess
        this.$message.success(res.msg)
        this.videoFlag = true
        this.getquerySn()
      }).catch(err => {
        this.videoFlag = true
      })
    },
    handleSuccess({result,header}){
      console.log(result,header);
    },
    beforeUpload(file) {
      this.SnForm.file = file
    },
    //SN导入确定事件
    uploadButton() {
      if (this.SnForm.file instanceof File) {
        if (this.snShow) {
          this.loadFormVisible = false
        } else {
          this.$message('存在导入文件未上传，请确认是否需要上传。')
        }
      } else {
        this.loadFormVisible = false
      }
    },
    //导出表单type选择
    async brandclassifySelect(val) {
      this.exporDisabled = true
      this.batchDisabled = true
      this.exporForm.username = ''//选中批次须把归属清空
      this.exporForm.batch = ''//选中归属须把批次清空
      switch (val) {
        case '3':
          this.exporDisabled = false
          break;
        case '4':
          this.batchDisabled = false
          break;
      }
    },
    //导出sn码信息
    getdownloadSn() {
      let exporForm = JSON.parse(JSON.stringify(this.exporForm))
      exporForm.userId = localStorage.getItem("ID")
      this.exporDisabled ? delete exporForm.username : exporForm.username
      this.batchDisabled ? delete exporForm.batch : exporForm.batch
      let loadingInstance = Loading.service({ target: '.content2' })
      downloadSn(exporForm).then(res => {
        window.open('https://' + res.data.url)
        this.$nextTick(() => {
          loadingInstance.close();
        });
      }).catch(err => {
        this.$nextTick(() => {
          loadingInstance.close();
        });
        err.code == 400 ? this.$message.error(err.msg) : ''
      })
    },
    //编辑sn
    geteditSn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let redactForm = JSON.parse(JSON.stringify(this.redactForm))
          redactForm.last_ip = sessionStorage.getItem("Ip")
          redactForm.userId = localStorage.getItem("ID")
          if (redactForm.username != this.userName) {//选中的归属变更时需要清除其他信息
            redactForm.batch = ''
            redactForm.classlevel = ''
            redactForm.sno = ''
            redactForm.realname = ''
            redactForm.phone = ''
            redactForm.phone_two = ''
          }
          editSn(redactForm).then(res => {
            this.$message.success(res.msg)
            this.getquerySn()
            this.redactFormVisible = false
          }).catch(err => {
            this.getquerySn()
            this.redactFormVisible = false
          })
        } else {
          return false
        }
      })
    },
    //id查询信息
    getqueryIdSn(id) {
      this.setQid = false
      this.redactFormVisible = true
      this.subjectId = id
      queryIdSn({ id: id }).then(({ data }) => {
        Object.keys(this.redactForm).forEach(key => { this.redactForm[key] = data[key] })
        this.redactForm.batch = data.batch
        this.affiliation.username = data.username
        this.affiliation.batch = data.batch
        this.userName = data.username
        this.setQid = data.is_active == 1
      })
    },
    //添加sn
    postAscription(fromName) {
      this.$refs[fromName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          postAscription(addForm).then(res => {
            this.$message.success(res.msg)
            this.getquerySn()
            this.dialogFormVisible = false
          }).catch(err => {
            this.getquerySn()
            this.dialogFormVisible = false
          })
        } else {
          return false
        }
      })
    },
    btnaddBrand() {
      this.dialogFormVisible = true
    },
    //设备维护获取归属用户信息
    getAscriptions() {
      getAscription({ userId: localStorage.getItem("ID") }).then(res => {
        //console.log('--------', res.data)
        this.snParams = res.data.sort((x, y) => {
          let reg = /[a-zA-Z0-9]/
          if (reg.test(x.username) || reg.test(y.username)) {
            if (x.username > y.username) {
              return 1
            } else if (x.username < y.username) {
              return -1
            } else {
              return 0
            }
          } else {
            return x.username.localeCompare(y.username)
          }
        })
      }).catch(err => {
        this.snParams = []
      })
    },
    //获取代理商信息
    getAgentUsers() {
      getAgentUser({ userId: localStorage.getItem("ID") }).then(res => {
        this.AgentUser = res.data
        getAscription({ userId: localStorage.getItem("ID") }).then(awd => {
          let adm = awd.data.filter(item => item.title == '超级管理员')
          this.agentsAdmin = [...adm, ...res.data]//添加及导入只显示代理商及超级管理员信息
        }).catch(err => {
          this.agentsAdmin = []
        })
      }).catch(err => {
        this.AgentUser = []
      })
    },
    //设备维护获取批次信息
    getBatch() {
      getBatchTwo({ userId: localStorage.getItem("ID") }).then(res => {
        this.redactParams = res.data
      }).catch(err => {
        this.redactParams = []
      })
    },
    getquerySn(params = this.listQuery) {
      querySn(params).then(res => {
        this.tableData = res.data
        this.total = res.total
        this.platterOptions = res.otherData.platterOptions
        this.setTopic(res.data)
        this.createMqtt()
      }).catch(err => {
        this.tableData = []
        this.total = 0
      })
    },
    setTopic(data) {
      let that = this
      data.forEach(function (element) {
        let topic = 'MQTT/T/UPDATE_DEVICE_INFO/SN_' + element.value
        if (!that.topicSends.includes(topic)) {
          that.topicSends.push(topic)
        }
      })
    },
    //搜索
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      switch (this.select) {
        case 'value':
          if (this.searchTable.length > 30) return this.$message('请输入正确的SN码')
          break;
      }
      this.listQuery = Object.assign({}, this.$options.data().listQuery, { [this.select]: this.searchTable || undefined })
      this.getquerySn();
    },
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
      })
    },
    redactFormclose() {
      this.$nextTick(() => {
        this.$refs.redactForm.resetFields();
        this.userName = ''
      })
    },
    exporFormclose() {
      this.exporForm = { type: '1', username: '', batch: '' }
      this.batchDisabled = true
      this.exporDisabled = true
    },
    snFormclose() {
      this.$nextTick(() => {
        this.snDisabled = true
        this.snShow = false
        this.videoFla = true
        this.$refs.snFormclose.resetFields();
      })
    },
    bathFormclose() {
      this.$nextTick(() => {
        this.gerentDisabled = true
        this.batchShow = false
        this.bathForm = { batch: '', pathname: '', file: {}, type: 0 }
        this.videoFla = true
      })
    },
    deleteFormclose() {
      this.$nextTick(() => {
        this.deleteFormVisible = false
        this.deleteForm = { file: {} }
        this.deleteData = {}
        this.deleteShow = false
      })
    },
    screenFormclose() {
      this.screenDate = { text: 1, value: '', id: 0 }
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getquerySn()
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getquerySn()
    },
    Refresh() {
      this.listQuery = {
        startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), value: undefined, username: undefined, batch: undefined,
        devices_version: undefined, appstore_version: undefined, store_version: undefined, is_online: undefined, sort: '', sno: undefined, s_realname: undefined, is_screen_lock: undefined
      }
      this.getquerySn()
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    },
    //批次创立更新导入模板
    handleDownload() {
      let tHeader = ["SN码", "班级", "学号", "姓名", "监护人1", "监护人2"];
      let filterVal = ["sn", "grade", "student", "name", "guardianOne", "guardianTwo"];
      let list = [{ "sn": 'QNS2HBYS0009', "grade": '英语一班', "student": '4321001', "name": '刘紫馨', "guardianOne": "1358580825", "guardianTwo": "18645661103" }]
      if(this.isAdmin) {
        tHeader = ["SN码","设备类别", "学习套餐", "可生成qid", "保修期(月)", "管控期(月)", "班级", "学号", "姓名", "监护人1", "监护人2", "其他备注"];
        filterVal = ["sn", "sn_type", "platter", "is_qid", "warranty", "control_time", "grade", "student", "name", "guardianOne", "guardianTwo"];
        list = [{ "sn": 'QNS2HBYS0009', "sn_type": '教管壹B端', "platter":'A', "is_qid":'是', "warranty": '3', "control_time": '3', "grade": '英语一班', "student": '4321001', "name": '刘紫馨', "guardianOne": "1358580825", "guardianTwo": "18645661103", "remark": '' }]
      }
      import("@/vendor/Export2Excel").then(excel => {
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({ header: tHeader, data, filename: '批次创立更新模板' });
        this.downloadLoading = false;
      });
    },
    downloadSnPlatter() {
      let tHeader = ["SN码", "设备类别", "学习套餐", "可生成qid"];
      let filterVal = ["sn", "sn_type", "platter", "is_qid"];
      let  list = [{ "sn": 'QNS2HBYS0009', "sn_type": '教管壹B端', "platter":'A', "is_qid":'是'}]
      import("@/vendor/Export2Excel").then(excel => {
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({ header: tHeader, data, filename: '设备类型与套餐更新模板' });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    /**创建mqtt**/
    createMqtt() {
      var mqtt; //mqtt 处理对象（全局变量）
      //创建链接，接收数据
      mqtt = new mqttHandle(this.topicSends);
      client = mqtt.createConnect();
      client.on("message", (topic, message) => {
        //数据分类
        try {
          let status = ""
          if (message.toString().length === 1) {
             status = message.toString() // status 1: 在线 2：离线
          }else {
            let jsonStatus = JSON.parse(message.toString())
             status = jsonStatus.message
          }
          let sn = topic.substring(topic.length - 12)
          this.tableData.forEach((item, index, arr) => {
            if(item.value == sn) {
              this.tableData[index].is_online = status
            }
          })
        } catch (error) {
          console.log("这是error", error)
        }
      });
    },

    //停止订阅mqtt
    disConnect() {
      if (client != null) {
        client.unsubscribe(this.topicSends);
        client = null;
      }
    }
  },
  beforeDestroy() {
    this.disConnect()
  },
}
</script>

<style lang="scss" scoped>
.img_go {
  transform: rotate(-360deg);
  transition: all 2s;
}
.img_stop {
  transition: all 2s;
}
.lock {
  color: #409eff;
}
.unlock {
  color: #4a3f72;
}
.sn_search_form {
  margin-bottom: 20px;
}
.sn {
  padding: 20px;

  .add_radios {
    margin-left: 60px;
    color: #606266;
    font-size: 14px;
  }
  .snElsx {
    .sn_select {
      // width: 79% !important;
      width: 61.5% !important;
      float: left;
    }
  }
}
.el-button--medium.is-circle {
  padding: 5px;
}
.icondian1 {
  font-size: 24px;
}
.state {
  display: flex;
  align-items: center;
}
.mask {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  margin: 0;
}
.sn-dialog {
  position: relative;
  margin: 0 auto 50px;
  border-radius: 2px;
  -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 50%;
  background: #ffffff;
}
.go {
  transform: rotate(360deg);
  transition: all 1s;
}
.details {
  font-size: 12px;
}
.cobyOrderSn {
  cursor: pointer;
  display: none;
}
.flex_spa:hover {
  .cobyOrderSn {
    display: inline;
  }
}
.screen {
  color: #c0c4cc;
  position: absolute;
  right: 45px;
  bottom: 5px;
  font-size: 12px;
}
.header_search {
  .searchI {
    //margin: 0 25px 10px 0;
  }
}
.state {
  width: 60%;
  // box-shadow: 2px 0px 12px rgb(0 0 0 / 10%);
  border-radius: 4px;
  background-image: none;
  background: #fff;
  border: 1px solid #dcdfe6;
}
</style>

<style scoped>
/deep/ .el-collapse-item__header {
  background-color: #f9f9f9;
}
/deep/ .el-collapse-item__content {
  padding-bottom: 0;
}
</style>

<style>
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  /* opacity: 0.75;
    line-height: 150px;
    margin: 0; */
}

/* .el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
} */

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}
</style>
